const app = getApp();

Page({
  data: {
    user: {},
    roleClass: '',
    roleName: '',
    showVerifyDialog: false, // 控制激活弹窗
    verifyCode: '',          // 验证码输入框内容
    verifyError: ''          // 错误提示
  },

  onLoad() {
    this.loadUserInfo();
  },

  loadUserInfo() {
    app.request({
      url: '/login/admin/checkLoginStatus',
      success: res => {
        if (res.code === 1) {
          const userRole = res.data.role;
          let roleClass = '';
          let roleName = '';

          if (userRole === 'ADMIN') {
            roleClass = 'normal';
            roleName = '普通管理员';
          } else if (userRole === 'SUPER_ADMIN') {
            roleClass = 'super';
            roleName = '超级管理员';
          }

          this.setData({ 
            user: res.data,
            roleClass: roleClass,
            roleName: roleName,
            showVerifyDialog: !res.data.active // 只要没激活就显示弹窗
          });

          app.globalData.user = res.data;
          wx.setStorageSync('user', res.data);
        } else {
          wx.showToast({ title: '加载失败', icon: 'none' });
        }
      },
      fail: () => {
        const app = getApp();
        app.globalData.user = null;
        app.globalData.token = null;
        app.globalData.adminToken = null;
        wx.removeStorageSync('user');
        wx.removeStorageSync('token');
        wx.removeStorageSync('adminToken');
        wx.reLaunch({
          url: '/pages/login/LoginSelectView/LoginSelectView'
        });
        wx.showToast({ title: '登录失败', icon: 'none' });
      }
    });
  },

  navigateToVerificationCodes() {
    wx.navigateTo({
      url: '/pages/admin/VerificationCodeView/VerificationCodeView'
    });
  },

  navigateToOrders() {
    wx.navigateTo({
      url: '/pages/admin/OrderListView/OrderListView'
    });
  },

  updatedUser(e) {
    const {avatarUrl } = e.detail;
    const updatedUser = {
      ...this.data.user,
      headimgurl: avatarUrl
    };
    app.request({
      url: '/admin/updatePersonalInformationById',
      method: 'POST',
      data: {...updatedUser,role:null},
      success: (response) => {
        if (response.code === 1) {
          this.setData({ user: updatedUser });
          app.globalData.user = updatedUser;
        } else {
          wx.showToast({ title: '更新失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
    wx.showModal({
      title: '补充信息',
      content: '请填写昵称以修改资料',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/admin/AdminEditNicknameView/AdminEditNicknameView'
          });
        }
      }
    });
  },

  syncWechatUserInfo(e) {
    const {avatarUrl } = e.detail;
    const updatedUser = {
      ...this.data.user,
      nickname: "微信用户",
      headimgurl: avatarUrl
    };

    app.request({
      url: '/admin/updatePersonalInformationById',
      method: 'POST',
      data: {...updatedUser,role:null},
      success: (response) => {
        if (response.code === 1) {
          this.setData({ user: updatedUser });
          app.globalData.user = updatedUser;
          wx.setStorageSync('user', updatedUser);
        } else {
          wx.showToast({ title: '更新失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });

    wx.showModal({
      title: '补充信息',
      content: '请填写昵称以完善资料',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/admin/AdminEditNicknameView/AdminEditNicknameView'
          });
        }
      }
    });

  },
  onInputCode(e) {
    const code = e.detail.value;
    this.setData({
      verifyCode: code,
      verifyError: ''  // 清除错误提示
    });
  },
  // 提交验证码
  submitVerifyCode() {
    const { verifyCode } = this.data;
    if (!verifyCode) {
      this.setData({ verifyError: '请输入验证码' });
      return;
    }

    app.request({
      url: '/login/admin/verify',
      method: 'POST',
      data: { code: verifyCode },
      success: res => {
        if (res.code === 1) {
          // 激活成功，更新用户状态
          const updatedUser = {
            ...this.data.user,
            active: true
          };
          this.setData({
            user: updatedUser,
            showVerifyDialog: false,
            verifyCode: '',
            verifyError: ''
          });

          app.globalData.user = updatedUser;
          wx.setStorageSync('user', updatedUser);

          wx.showToast({ title: '激活成功' });
        } else {
          this.setData({ verifyError: res.msg || '验证码错误，请重试' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: res => {
        if (res.confirm) {
          app.request({
            url: '/login/logout',
            success: logoutRes => {
              wx.showToast({ title: '已退出' });
              const app = getApp();
              app.globalData.user = null;
              app.globalData.token = null;
              app.globalData.adminToken = null;
              wx.removeStorageSync('user');
              wx.removeStorageSync('token');
              wx.removeStorageSync('adminToken');
              wx.reLaunch({
                url: '/pages/login/LoginSelectView/LoginSelectView'
              });
            },
            fail: () => {
              wx.removeStorageSync('user');
              wx.removeStorageSync('token');
              wx.removeStorageSync('adminToken');
              wx.reLaunch({
                url: '/pages/login/LoginSelectView/LoginSelectView'
              });
            }
          });
        }
      }
    });
  },
  getWebLoginCode() {
    const that = this;
    
    // 调用wx.login接口
    wx.login({
      success(res) {
        if (res.code) {
          // 将获取到的code放到剪切板上
          wx.setClipboardData({
            data: res.code,
            success() {
              wx.showToast({
                title: '登录码已复制',
                icon: 'success'
              });
            },
            fail() {
              wx.showToast({
                title: '复制失败，请稍后再试',
                icon: 'none'
              });
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg);
          wx.showToast({
            title: '获取登录验证码失败',
            icon: 'none'
          });
        }
      },
      fail() {
        wx.showToast({
          title: '请求登录失败',
          icon: 'none'
        });
      }
    });
  },
});